package com.woniuxy.course.utils;

import com.woniuxy.commons.dto.TreeObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 王光强
 * @date 2020/7/24 0024-15:53
 */
public class TreeObjectUtils {
    private List<TreeObject> rootNodesList;//根节点列表

    private List<TreeObject> childNodesList;//身体节点列表

    public TreeObjectUtils(List<TreeObject> rootNodesList, List<TreeObject> childNodesList) {
        this.rootNodesList = rootNodesList;
        this.childNodesList = childNodesList;
    }

    /**
     * 生成树状结构对象
     * @return
     */
    public List<TreeObject> getTreeObjectList() {
        //子节点列表不等于null或者个数不为空，将子节点封装到对应根节点
        if (childNodesList != null && !childNodesList.isEmpty()) {
            //创建一个map用于保存已经处理过的childNodesList中的TreeObject的id
            HashMap<Object, Object> childNodesHashMap = new HashMap<>(childNodesList.size());
            //循环根节点列表，将子节点列表封装到对应的根节点TreeObject对象中
            rootNodesList.forEach(rootNode -> getChild(rootNode, childNodesHashMap));
            return rootNodesList;
        }
        return null;
    }

    //将身体节点通过parentId识别封装到各自对应的父节点treeObject中
    private void getChild(TreeObject rootNode, Map<Object, Object> childNodesHashMap) {
        //创建一个list来保存每个根节点中对应的子节点
        List<TreeObject> childList = new ArrayList<>();
        childNodesList.stream()
                .filter(childNode -> !childNodesHashMap.containsKey(childNode.getCategoryId()))//过滤处理过的childNode
                .filter(childNode -> childNode.getParentId()==(rootNode.getCategoryId()))//判断是否根节点的子节点
                .forEach(childNode -> {
                    childNodesHashMap.put(childNode.getCategoryId(), childNode.getParentId());//添加处理子节点信息
                    getChild(childNode, childNodesHashMap);//递归设置该子节点的子节点列表
                    childList.add(childNode);//添加该子节点到对应的根节点列表
                });
        rootNode.setChildNodeList(childList);
    }

}
